<template>
    <view>
        <search-input @confirmSearch="confirmSearch" v-model="searchVal"/>
        <view class="search-history common-interval" v-if="isShowHistory">
            <view class="search-title common-flex-between">
                <text class="title">搜索历史</text>
                <text class="one one-delete icon-btn" @tap.stop="delSearchHistory"/>
            </view>
            <view class="history-label">
                <text class="label-item"
                      @tap="historySearch(item)"
                      v-for="(item, index) in labelList"
                      :key="index">
                    {{item.length <=6 ? item : item.slice(0,5)+ '...'}}
                </text>
            </view>
        </view>
        <view v-else class="search-result">
            <gwCardTabs
                    @tabChange="tabChange"
                    :tabsTitle="tabsTitle"
                    :typeVal="type"
                    width="690rpx"
                    padding="20rpx 30rpx"
                    class="tab-wrapper"
            >
                <mescroll-uni
                              @down="downCallback"
                              @up="upCallback"
                              :down="downOption"
                              :up="upOption"
                              top="180"
                              class="mescroll-flex"
                              @init="mescrollInit">
                    <view class="search-result-wrapper">
                        <view
                                v-for="(item, index) in bookList"
                                :key="index"
                        >
                            <view class="common-division card-division"/>
                            <gw-book-card
                                    v-if="type==='books'"
                                    :item="item"
                                    @linkTo="linkTo"
                                    @updateBooks="updateBooks"
                            />
                            <book-card
                                    v-else
                                    :item="item"
                                    :id-name="type"
                            />
                        </view>
                    </view>
                </mescroll-uni>
            </gwCardTabs>
        </view>
    </view>
</template>

<script>
    import searchInput from './search-input'
    import gwCardTabs from '@/pages/components/gw-card-tabs'
    import bookCard from './book-card'
    import gwBookCard from '@/pages/components/gw-book-card'
    import MescrollUni from "@/components/mescroll-uni/mescroll-uni.vue";
    import service from "@/service";

    export default {
        name: "index",
        components: {
            searchInput, gwCardTabs, gwBookCard, MescrollUni, bookCard
        },
        data() {
            return {
                searchVal: '',
                isShowHistory: true,
                bookList: [],
                dataList: [],
                page: 1,
                limit: 10,
                downOption: {
                    auto: false,
                },
                upOption: {
                    use: true, // 是否启用上拉加载; 默认true
                    auto: true, // 是否在初始化完毕之后自动执行上拉加载的回调; 默认true
                    page: {
                        num: 0, // 当前页码,默认0,回调之前会加1,即callback(page)会从1开始
                        size: 10 // 每页数据的数量,默认10
                    },
                    noMoreSize: 5, // 配置列表的总数量要大于等于5条才显示'-- END --'的提示
                    empty: {
                        icon: 'https://img.thumbrary.com/empty.png',
                        tip: `没有找到相关${this.type === 'books' ? '绘本' : '数据'}，建议换个关键词试试`
                    },
                    offset: 130,
                    textNoMore: '我是有底线的 >_<'
                },
                mescroll: null,
                labelList: ['格林童话'],
                type: 'books',
                typeVal: ['books', 'author', 'roles', 'theme', 'award'],
                tabsTitle: [
                    {
                        type: 'books',
                        name: '绘本'
                    },
                    {
                        type: 'author',
                        name: '作者'
                    },
                    {
                        type: 'roles',
                        name: '图画角色'
                    },
                    {
                        type: 'theme',
                        name: '主题角色'
                    },
                    {
                        type: 'award',
                        name: '奖项'
                    },
                ]
            }
        },
        onShow() {
            // 获取历史搜索记录
            let searchHistory = uni.getStorageSync('searchHistory');
            this.labelList = searchHistory ? searchHistory.split(',') : [];
        },
        onLoad(params){
            this.type = this.typeVal.includes(params.type) ? params.type : 'books';
        },
        methods: {
            confirmSearch(value) {
                // 添加搜索记录
                if(value) {
                    this.labelList.unshift(value);
                    this.labelList = [...new Set(this.labelList)];
                    if (this.labelList.length > 10) {
                        this.labelList = this.labelList.slice(0, 10);
                    }
                    uni.setStorageSync('searchHistory', this.labelList.join(','));
                }
                this.isShowHistory = false;
                this.bookList = [];
                this.page = 1;
                this.mescroll && this.mescroll.resetUpScroll();
                (this.type === 'books') ?  this.getBooks() : this.getClassList()
            },
            getClassList () {
                uni.showLoading({
                    title: '加载中',
                });
                service.homeService.getClassList({
                    data: {
                        page: this.page,
                        limit: this.limit,
                        [this.type+'Name']: this.searchVal
                    },
                    type: this.type,
                    success: res => {
                        uni.hideLoading();
                        if (res.code === 200) {
                            let data = res.result.data || [];
                            this.page > 1 ? this.bookList.push(...data) : this.bookList = data;
                            this.mescroll && this.mescroll.endBySize(data.length, res.result.num);
                        } else {
                            uni.showToast({
                                title: `${res.resultMsg}`,
                                duration: 2500,
                                icon: 'none'
                            });
                        }
                    },
                    fail: ()=>{
                        uni.hideLoading();
                    },
                    complete: () => {
                    },
                });
            },
            // 删除历史记录
            delSearchHistory() {
                uni.clearStorageSync('searchHistory');
                this.labelList = [];
            },
            tabChange(item) {
                this.type = item.type;
                this.bookList = [];
                this.page = 1;
                this.mescroll && this.mescroll.resetUpScroll();
            },
            historySearch(item) {
                this.searchVal = item;
                this.isShowHistory = false;
            },
            mescrollInit(mescroll) {
                this.mescroll = mescroll;
            },
            downCallback(mescroll) {
                this.bookList = [];
                this.page = 1;
                mescroll.resetUpScroll();
            },
            upCallback(mescroll) {
                this.page = mescroll.num;
                this.type === 'books' ?  this.getBooks() : this.getClassList()
            },
            linkTo(item) {
                uni.navigateTo({
                    url: `../../components/gw-book-detail?booksId=${item.booksId}`
                })
            },
            updateBooks() {
                this.type === 'books' ?  this.getBooks({
                    page: 1,
                    limit: this.bookList.length,
                    nameAll: this.searchVal
                }) : this.getClassList()
            },
            getBooks(para) {
                // 获取名片完整信息
                uni.showLoading({
                    title: '加载中',
                });
                let params = para || {
                    page: this.page,
                    limit: this.limit,
                    nameAll: this.searchVal
                };
                service.homeService.getBooks({
                    data: params,
                    success: res => {
                        uni.hideLoading();
                        if (res.code === 200) {
                            let data = res.result.data || [];
                            (this.page > 1 && !para) ? this.bookList.push(...data) : this.bookList = data;
                            this.mescroll && this.mescroll.endBySize(data.length, res.result.num);
                        } else {
                            uni.showToast({
                                title: `${res.resultMsg}`,
                                duration: 2500,
                                icon: 'none'
                            });
                        }
                    },
                    fail: ()=>{
                        uni.hideLoading();
                    },
                    complete: () => {
                    },
                });
            },
        }
    }
</script>

<style scoped lang="scss">
    .search-history {
        margin-top: 190rpx;
    }

    .search-title {
        margin-bottom: 40rpx;

        .title {
            color: #333333;
            font-size: 32rpx;
        }

        .icon-btn {
            color: #666666;
            font-size: 40rpx;
        }
    }

    .history-label {
        flex-wrap: wrap;
        display: flex;

        .label-item {
            width: 220rpx;
            height: 68rpx;
            background: rgba(249, 249, 249, 1);
            border-radius: 34rpx;
            line-height: 68rpx;
            text-align: center;
            color: #666666;
            margin-top: 20rpx;
            margin-right: 15rpx;

            &:nth-of-type(3n) {
                margin-right: 0;
            }
        }
    }

    .search-result {
        top: 110rpx;
        position: relative;
        &-wrapper {
            padding: 20rpx 30rpx 10rpx 30rpx;
            box-sizing: border-box;
            .card-division {
                width: 750rpx;
                margin-left: -30rpx;
                margin-bottom: 18rpx;
            }
        }
    }
</style>